import React, { PureComponent } from 'react';
import { Icon, Table, TreeSelect, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import {worker} from "../../utils/worker"
import "./form.less"
import "../../Common.less"
class TopComponentForm extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            type: "",
            mass: false,
            treeData: [],
            originalData: [],
            sectionId: null,
            selectedRowKeys: [],
            selectActive: true,
            bridgeList: [],
            data: [],
            count: 0,
            name: "",
            columns: [],
            allChecked: false,
            st: null,
            qString: "",
            pagination: {
                pageSize: 5,
                pageNum: 1
            },
            loading: false,
            total: 0,
        }
        this.paginationChange = this.paginationChange.bind(this)
        this.getData = this.getData.bind(this);
        this.editComponent = this.editComponent.bind(this);
        this.onSelect = this.onSelect.bind(this)
        this.onSelectChange = this.onSelectChange.bind(this)
        this.onConfirm = this.onConfirm.bind(this)
        this.absReset = this.absReset.bind(this)
        this.refresh = this.refresh.bind(this)
        this.massEditProps=this.massEditProps.bind(this)
        this.massEditProps2=this.massEditProps2.bind(this)
        this.editComponentProps=this.editComponentProps.bind(this)

    }
    
    refresh() {
        this.setState({
            selectedRowKeys:[]
        })
        this.getData()
    }
    editComponent(e, item) {
        const {modalContext}=this.props;
        let { bridgeId, operateType } = this.state;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        e.preventDefault();
        this.setState({
            sectionId: item.id,
            mass: false
        })

        if (modalContext) {
            modalContext.updateModal({
                visible: true,
                title: "选择构件",
                event: { code: "structureSelect" },
                extra: {
                    "nodeType": 3,
                    operateType: 'cusProps',
                    selectionOrSpanIds: [item.id],
                    definitionIds: [],
                    bridgeId,
                    type: "top",
                    spanType: item.spanType
                }
            });
        }
    }
    async getData() {
        this.setState({
            loading:true
        })
        let { selectAll, selectedRowKeys, sid,bridgeId } = this.state;
        if(!bridgeId){
            return;
        }
        const {structureTree}=this.props;
        let extra = {}
        let res = await this.props.getTopSelections({ bridgeId, sid })
        
        if (res && res.length) {
            const len=res.length
            for (let i = 0; i < len; i++) {
                const item = res[i];
                if(item.definitionTreeIds&&item.definitionTreeIds.length){
                    let arr=[]
                    const len2=item.definitionTreeIds.length
                    for (let i = 0; i < len2; i++) {
                        let item2 = item.definitionTreeIds[i];
                        const obj=await worker.getTreeNode(structureTree,item2)
                        arr.push({
                            definitionTreeId:item2,
                            title:obj.title,
                            code:obj.code
                        })
                    }
                    item.structures=arr;
                }
               
                if (selectAll) {
                    selectedRowKeys.push(item.id)
                }
            }
            extra.selectedRowKeys = selectedRowKeys
            this.setState({
                loading: false,
                data: res,
                originalData: res,
                total: res ? res.length : 0,
                ...extra
            })


        } else {
            this.setState({
                loading: false,
                originalData: [],
                data: [],
                total: 0
            })
        }
    }
    absReset() {
        this.setState({
            selectedRowKeys: [],
            operateType: null,
            sid: null,
            selectAll: null,
            bridgeId: null
        })
    }
    onConfirm(params) {
        return new Promise((resolve, reject) => {
            let selectionOrSpanIds = []
            let definitionIds = []
            if (!classedStructures || !classedStructures.length) {
                notification.warn({ message: "请先选择构件" })
                return;
            }
            const {treeContext}=this.props;
            let { selectedRowKeys, data, bridgeId, operateType } = this.state;
            if (data && data.length) {
                if (selectedRowKeys && selectedRowKeys.length) {
                    const len= data.length
                    for (let i = 0; i < dlen; i++) {
                        let item = data[i];
                        const len2=selectedRowKeys.length
                        for (let j = 0; j < len2; j++) {
                            let item2 = selectedRowKeys[j];
                            if (item.id == item2) {
                                selectionOrSpanIds.push(item.id)
                            }
                        }
                    }
                }

            }

            this.props.addDefinitionInstance({
                operateType: operateType || "cover",
                selectionOrSpanIds,
                definitionIds,
                bridgeId,
                "type": "top"
            }, res => {

                if (res && res.length) {
                    const len=res.length;
                    for (let i = 0; i < len; i++) {
                        let obj = res[i];
                        if (obj.data && obj.data.length) {
                            const len2=obj.data.length
                            for (let i = 0; i < len2; i++) {
                                let unit = obj.data[i];
                                let { definitionInstances, selectionOrSpanId } = unit;
                                if (definitionInstances && definitionInstances.length) {
                                    const len3= definitionInstances.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = definitionInstances[i];
                                        item.title = item.instanceName;
                                        item.key = 'topStructureComponentUnit' + item.id;
                                        item.type = "top"
                                        item.eventType = 'topStructureComponentUnit'
                                        item.eventKey = 'topStructureComponentUnit'
                                        item.checkable = true
                                        item.selectable = true
                                        item.isLeaf = true
                                    }
                                }
                                treeContext.updateTreeNode("topStructureDirec" + selectionOrSpanId, definitionInstances)
                            }
                        }

                    }
                }

                resolve()
            }, err => {
                reject()
            })
        })
    }
    async paginationChange(pagination, filters, sorter, extra) {
        await this.setState({
            pagination: {
                ...this.state.pagination,
                pageNum: pagination.current
            }
        })
        this.getData()
    }
    async editComponentProps(e,item){
        e.preventDefault()
        let { bridgeId, data } = this.state;
        const selectedRowKeys=[item.id]
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [], arr2 = [],arr3=[],arr4=[];
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                let obj = data.find(item2 => item2.id == item)
                if(!obj.definitionIds){
                    notification.warn({ message: "请先添加构件!" })
                    return;
                }
                arr.push(obj.stype)
                arr2.push(obj.definitionIds)
                arr3.push(...obj.definitionIds)
                arr4.push(...obj.definitionInstanceIds)
            }
        }
        const isAllSame=!arr2.some(function (item, index) {
            return item.toString() !== arr2[0].toString();
        });
        if(!isAllSame){
            notification.warn({ message: "只能选择同类构件!" })
            return;
        }
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2= selectedRowKeys.length
                    for (let j = 0; j < len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                        }
                    }
                }
            }

        }
        let res2 = await this.props.getBottomProperty({
            definitionIds: Array.from(new Set(arr3)),
            definitionInstanceIds: arr4,
            type:"top"
        })
        if (res2&&res2.length&&this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "自定义属性编辑",
                event: { code: "cusTable",width:1200 },
                extra:{
                    designedStructures:res2,
                    type:"top"
                }
            });
        }else{
            notification.warn({ message: "未设置属性!" })
        }
    }
    async componentDidMount() {
        let { project, bridgeData, currentBridge } = this.props;
        if (this.props.onLoaded) {
            this.props.onLoaded(this);
        }
        if (bridgeData || currentBridge) {
            const curBri = bridgeData || currentBridge
            await this.setState({
                sid: curBri.sid || "",
                operateType: curBri.operateType || "",
                selectedRowKeys: curBri.selectedRowKeys || [],
                selectAll: curBri.selectAll || "",
                bridgeId: curBri.bridgeId || curBri.id || ""
            })
            this.getData()
        }

        if (this.props.bridgeMainAndChild) {
            let res = await this.props.bridgeMainAndChild({ projectId: project.id })
            this.setState({
                treeData: res && res.length ? await worker.loopTreeNode4(JSON.parse(JSON.stringify(res).replace(/bridges/g, 'children')),true) : []
            })
        }
        const columns = [
            {
                title: '联号',
                dataIndex: 'selectionName',
                render: (text, record) => text + "(" + record.express + ")"
            },
            {
                title: '起止桩号',
                dataIndex: 'boundary',
            },

            {
                title: '构件',
                dataIndex: 'structures',
                render: (text, record) => text && text.length ? text.map((item, index) => <span className="structure" key={'str' + index}>{item.title + ':' + record['instanceNames'][index]}</span>) : ''

            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => <span className="operate"><a onClick={(e) => this.editComponent(e, record)}><Icon type="edit" />&nbsp;设置构件</a><a style={{marginLeft:"5px"}} onClick={(e) => this.editComponentProps(e, record)}><Icon type="edit" />&nbsp;设置属性</a></span>,
            },
        ];
        this.setState({
            columns
        })
    }
    async onSelect(e) {
        await this.setState({
            bridgeId: e
        })
        this.getData()
    }
    massEditProps(e) {
        e.persist();
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [],arr2=[],arr3=[]
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                let obj = data.find(item2 => item2.id == item)
                arr.push(obj.spanType)
                arr3.push(obj.definitionTreeId)
            }
        }
        arr = Array.from(new Set(arr))
        this.setState({
            mass: true
        })
        
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2=selectedRowKeys.length
                    for (let j = 0; j < len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                            if(item.definitionIds){
                                arr.push(...item.definitionIds)
                            }
                        }
                    }
                }
            }
        }
        if (this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "构件属性编辑",
                event: { code: "structureSelect" },
                extra: {
                    "nodeType": 3,
                    operateType: 'cusProps',
                    selectionOrSpanIds,
                    definitionIds: selectedRowKeys,
                    bridgeId,
                    type: "top",
                    spanType: arr[0]
                }
            });
        }
    }
    async massEditProps2(e){
        e.persist();
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        const {extra}=this.props;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [], arr2 = [],arr3=[],arr4=[];
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                let obj = data.find(item2 => item2.id == item)
                if(!obj.definitionIds){
                    notification.warn({ message: "请先添加构件!" })
                    return;
                }
                arr.push(obj.stype)
                
                arr2.push(obj.definitionIds)
                arr3.push(...obj.definitionIds)
                arr4.push(...obj.definitionInstanceIds)
            }
        }
        const isAllSame=!arr2.some(function (item, index) {
            return item.toString() !== arr2[0].toString();
        });
        if(!isAllSame){
            notification.warn({ message: "只能选择同类构件!" })
            return;
        }
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2= selectedRowKeys.length
                    for (let j = 0; j < len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                        }
                    }
                }
            }

        }
        let res2 = await this.props.getBottomProperty({
            definitionIds: Array.from(new Set(arr3)),
            definitionInstanceIds: arr4,
            type:"top"
        })
        if (res2&&res2.length&&this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "自定义属性编辑",
                event: { code: "cusTable",width:1200 },
                extra:{
                    designedStructures:res2,
                    type:"top"
                }
            });
        }else{
            notification.warn({ message: "未设置属性!" })
        }
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
   
    render() {
        let { columns, loading,data, treeData, selectedRowKeys, selectActive } = this.state
        const { currentBridge,commondShow } = this.props;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="absMiddle topComponent">
                <div className="absMiddle sorter">
                    <Form style={{ padding: "15px 15px" }}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}
                    >
                        <Form.Item style={{alignItems:"center"}} label='桥梁'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '桥梁' }
                                ],
                                initialValue: currentBridge ? (currentBridge.bridgeId ? currentBridge.bridgeId : currentBridge.id) : undefined
                            })(
                                <TreeSelect
                                    showSearch
                                    treeNodeFilterProp="name"
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    placeholder="请选择桥梁"
                                    treeData={treeData}
                                    allowClear
                                    treeDefaultExpandAll
                                    onSelect={this.onSelect}
                                ></TreeSelect>
                            )}
                        </Form.Item>
                       <div className="btnBox">
                      
                        <Button disabled={!selectedRowKeys.length} onClick={e => this.massEditProps(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量设置构件</Button>
                        <Button disabled={!selectedRowKeys.length} onClick={e => this.massEditProps2(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量设置属性</Button>
                       </div>
                    </Form>

                </div>
                <Table loading={loading} scroll={{ y: commondShow?280:360 }} pagination={false} className="absMiddle" rowSelection={selectActive ? rowSelection : false} rowKey={record => record.id} loading={loading} columns={columns} dataSource={data} />
            </div>
        );
    }
}

export default connect(
    ({
        dict:{structureTree},
        structure: { classedStructures },
        bridge: { currentBridge }
    }) => {
        return {
            classedStructures, currentBridge,structureTree
        };
    },
    dispatch => ({
        addDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/addDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        getBottomProperty: (values) => dispatch({
            type: 'structure/getBottomProperty',
            payload: values
        }),
        bridgeMainAndChild: (values) => dispatch({
            type: 'bridge/bridgeMainAndChild',
            payload: values
        }),
        getTopSelections: (values) => dispatch({
            type: 'refSpans/getTopSelections',
            payload: values
        }),
    })
)(Form.create('TopComponentForm', {

})(TopComponentForm));